<template>
  <div>
    <!-- 报价 -->
    <!-- {{qutoData}} -->
    <el-descriptions title="询价信息" :labelStyle="{ width: '90px' }" :column="2">
      <el-descriptions-item label="型号">
        <DescriptionsTooltip :value="queryInfo.partnumber">{{ queryInfo.partnumber }}</DescriptionsTooltip>
      </el-descriptions-item>
      <el-descriptions-item label="品牌">
        <DescriptionsTooltip :value="queryInfo.brand">{{ queryInfo.brand }}</DescriptionsTooltip>
      </el-descriptions-item>
      <el-descriptions-item label="数量">{{ queryInfo.quantity }}</el-descriptions-item>
      <el-descriptions-item label="批次">{{ queryInfo.dateCode }}
      </el-descriptions-item>
      <el-descriptions-item label="封装">
        <DescriptionsTooltip :value="queryInfo.package">{{ queryInfo.package }}</DescriptionsTooltip>
      </el-descriptions-item>
      <el-descriptions-item label="接受价">
        <span style="color:#e02020;">{{ Number.isInteger(queryInfo.adoptPrice || queryInfo.unitPrice) ? (queryInfo.adoptPrice || queryInfo.unitPrice).toFixed(2) : (queryInfo.adoptPrice || queryInfo.unitPrice) }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="币种">{{
        queryInfo.currency == 1 || queryInfo.currency == 'CNY' ? "人民币" : "美元"
      }}</el-descriptions-item>
      <el-descriptions-item label="交货日期">
        <DescriptionsTooltip :value="queryInfo.deliveryDate">{{ queryInfo.deliveryDate }}</DescriptionsTooltip>
      </el-descriptions-item>
      <el-descriptions-item label="交货地">{{
        queryInfo.deliveryPlace || queryInfo.district == "FArea01" ? "中国大陆" : "中国香港"
      }}</el-descriptions-item>
      <el-descriptions-item label="包装">
        <DescriptionsTooltip :value="queryInfo.packing">{{ queryInfo.packing }}</DescriptionsTooltip>
      </el-descriptions-item>
      <el-descriptions-item label="发票类型">
        <DescriptionsTooltip :value="queryInfo.invoiceType">{{ queryInfo.invoiceType }}</DescriptionsTooltip>
      </el-descriptions-item>
      <el-descriptions-item label="剩余报价时间" v-if="queryInfo.quoteRemainMin">
        <span style="color: #FF0000">{{
          (0 >= queryInfo.quoteRemainMin * 1
            ? "已结束"
            : queryInfo.quoteRemainMin) | manageTime
        }}</span>
      </el-descriptions-item>
    </el-descriptions>
    <label class="suptitle">报价信息</label>
    <el-form :model="ruleForm" :rules="rules" ref="form" label-width="100" label-position="left">
      <el-form-item label="" v-show="isShowCheckbox || isActurl || this.qutoData.inquiryType == '实单询价'" class="isAccept">
        <el-checkbox v-model="isAccept" @change="handleAccept" name="quto">
          一键同意
        </el-checkbox>
      </el-form-item>
      <el-form-item label="币种：" prop="currency">
        <!-- <template v-if="isAccept">
          {{ruleForm.currency=="CNY"||ruleForm.currency=="1"?"人民币":"美元"}}
        </template>
        <template v-else> -->
        <el-select v-model="ruleForm.currency" @change="changeOptions($event)" class="input">
          <el-option label="人民币" v-if="!isSommer || isHome" value="CNY"></el-option>
          <el-option label="美元" v-if="!isSommer || isHome" value="USD"></el-option>
          <el-option label="人民币" v-if="isSommer || isHome" value="1"></el-option>
          <el-option label="美元" v-if="isSommer || isHome" value="2"></el-option>
        </el-select>

        <!-- </template> -->
      </el-form-item>
      <el-form-item label="单价：" prop="unitPrice">
        <!-- <template v-if="isAccept">
          {{ruleForm.unitPrice}}
        </template>
        <template v-else> -->
        <!-- <el-input-number :controls="false" v-inpNum align="left" :max="999999999" :precision="6"
          v-model="ruleForm.unitPrice" style="margin-left: 27px;"></el-input-number> -->
        <el-input v-model="ruleForm.unitPrice" @blur="handleBlur" @input="handleInput" class="input"></el-input>
        <!-- </template> -->
      </el-form-item>
      <el-form-item label="报价数量：" prop="quantity">
        <!-- <template v-if="isAccept">
          {{ruleForm.quantity}}
        </template>
        <template v-else> -->
        <el-input-number :controls="false" v-inpNum.noquto :precision="0" v-model="ruleForm.quantity"></el-input-number>
        <!-- </template> -->
      </el-form-item>
      <el-form-item label="交货日期：" prop="deliveryDate">
        <!-- <template v-if="isAccept">
          {{ruleForm.quantity}}
        </template>
        <template v-else> -->
        <el-date-picker v-model="ruleForm.deliveryDate" :picker-options="pickerOption" type="date"
          value-format="yyyy-MM-dd" placeholder="选择日期">
        </el-date-picker>
        <!-- </template> -->
      </el-form-item>
      <el-form-item label="批次：" prop="dateCode" class="dateCode">
        <!-- <template v-if="isAccept">
          
        </template>
        <template v-else> -->
        <el-input v-model="ruleForm.dateCode" maxlength="30" type="text" show-word-limit class="dataCodeinput"></el-input>
        <!-- </template> -->
      </el-form-item>
      <el-form-item label="交货地：" prop="deliveryPlace">
        <!-- <template v-if="isAccept">
          {{ruleForm.deliveryPlace=="FArea01"?"国内":"香港"}}
        </template>
        <template v-else> -->
        <el-select v-model="ruleForm.deliveryPlace" class="place">
          <el-option label="中国大陆" value="FArea01"></el-option>
          <el-option label="中国香港" value="FArea02"></el-option>
        </el-select>
        <!-- </template> -->
      </el-form-item>
      <el-form-item label="报价有效期：" prop="termDate" v-show="false">
        <!-- <template v-if="isAccept">
          {{ruleForm.quantity}}
        </template>
        <template v-else> -->
        <el-date-picker v-model="ruleForm.termDate" :picker-options="pickerOption" type="date" value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker>
        <!-- </template> -->
      </el-form-item>
      <el-form-item label="报价公司：" prop="supplierID">
        <el-select v-model="ruleForm.supplierID" @change="handlesupplierChange">
          <el-option v-for="item in suppliers" :label="item.supplierName" :value="item.supplierID" :key="item.supplierID">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="foot" v-loading="btnLoading">
      <el-button type="primary" size="small" @click="handleConfirmQuto">
        确认报价</el-button>
      <!-- <el-button plain size="small" @click="$emit('close')">取消</el-button> -->
      <el-button size="small" class="resletBtn" @click="handleNotQuto">取消报价</el-button>
      <!-- <el-button
        v-show="!isSommer && !isAccept"
        type="primary"
        size="small"
        @click="handleNotQuto"
        >无法报价</el-button
      > -->
    </div>
  </div>
</template>
<script>
import {
  TaskQuote,
  UnableQuote,
  SearchQuote,
  getSuppliers,
  SearchClaim,
} from "@/api/scsapi/index";
import DescriptionsTooltip from "@/components/DescriptionsTooltip/index.vue";
import { mapGetters } from "vuex";
import { nextDate } from "@/utils";
export default {
  name: "quto",
  components: {
    DescriptionsTooltip
  },
  props: {
    isShowCheckbox: {
      default: true,
      type: Boolean,
    },
    isActurl: {
      default: true,
      type: Boolean,
    },
    qutoData: {
      default: () => {
        return {};
      },
      type: Object,
      required: true,
    },
    isSommer: {
      default: false,
      type: Boolean,
    },
    isHome: {
      default: false,
      type: Boolean,
    }
  },
  data() {
    return {
      // 是否同意接受价
      isAccept: false,
      btnLoading: false,
      ruleForm: {
        unitPrice: undefined,
        currency: undefined,
        quantity: undefined,
        deliveryDate: undefined,
        dateCode: undefined,
        deliveryPlace: undefined,
        district: undefined,
        supplierID: undefined,
        supplierName: undefined,
        summary: "",
        termDate: nextDate(), // 请选择报价有效期
      },

      pickerOption: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },

      rules: {
        unitPrice: [{ required: true, message: "请输入报价", trigger: "blur" }],
        currency: [
          { required: true, message: "请选择币种", trigger: "change" },
        ],
        quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
        deliveryDate: [
          { required: true, message: "请选择交货日期", trigger: "change" },
        ],
        termDate: [
          { required: true, message: "请选择报价有效期", trigger: "change" },
        ],
        dateCode: [
          // { required: true, message: '请输入批次', trigger: 'blur' },
          { min: 0, max: 50, message: "长度0-50", trigger: "blur" },
        ],
        deliveryPlace: [
          { required: true, message: "请选择交货地", trigger: "change" },
        ],
        supplierID: [
          { required: true, message: "请选择报价公司", trigger: "change" },
        ],
      },
      suppliers: [],
    };
  },
  computed: {
    ...mapGetters(["id"]),
    queryInfo() {
      if (!this.isSommer) {
        return {
          partnumber: this.qutoData.product_partnumber || this.qutoData.partNumber,
          brand: this.qutoData.product_brand || this.qutoData.brand,
          quantity: this.qutoData.quantity,
          dateCode: this.qutoData.product_dateCode || this.qutoData.dateCode,
          package: this.qutoData.product_package || this.qutoData.package,
          adoptPrice: this.qutoData.adoptPrice,
          currency: this.qutoData.currency,
          deliveryDate: this.qutoData.deliveryDate,
          deliveryPlace: this.qutoData.deliveryPlace,
          district: this.qutoData.district,
          packing: this.qutoData.product_packing || this.qutoData.packing,
          quoteRemainMin: this.qutoData.quoteRemainMin,
          invoiceType: this.qutoData.invoiceType,
          unitPrice: this.qutoData.unitPrice
        };
      } else {
        return {
          partnumber: this.qutoData.partNumber,
          brand: this.qutoData.brand,
          quantity: this.qutoData.quantity,
          dateCode: this.qutoData.dateCode,
          package: this.qutoData.package,
          adoptPrice: this.qutoData.unitPrice,
          currency: this.qutoData.currency,
          deliveryDate: this.qutoData.deliveryDate,
          deliveryPlace: this.qutoData.deliveryPlace,
          packing: this.qutoData.packing,
          quoteRemainMin: this.qutoData.remainQuoteDuration,
          invoiceType: this.qutoData.invoiceType,

        };
      }
    },
  },
  created() {
    getSuppliers().then((res) => {
      if (res.status == 200) {
        this.suppliers = res.data;
        if(this.suppliers.length === 1){
          console.log('tag11111', this.suppliers)
          this.suppliers.map(x=>{
            this.ruleForm.supplierID = x.supplierID;
            this.ruleForm.supplierName = x.supplierName
          })
        }
      }
    });
  },
  mounted() {
    // console.log('tag', this.suppliers)
    // console.log('this.qutoData', this.qutoData)
    // console.log(this.queryInfo)
    // this.$set(this.ruleForm, "unitPrice", this.qutoData.adoptPrice ? this.qutoData.adoptPrice : 0);
    this.$set(this.ruleForm, "currency", (this.qutoData.currency == 1 || this.qutoData.currency == 'CNY') ? "人民币" : "美元");
    // this.$set(this.ruleForm, "quantity", this.qutoData.quantity);
    this.$set(this.ruleForm, "deliveryDate", this.qutoData.deliveryDate);
    this.$set(this.ruleForm, "dateCode", this.qutoData.dateCode);
    this.$set(this.ruleForm, "deliveryPlace", this.qutoData.deliveryPlace || this.qutoData.district);
  },
  methods: {
    handleInput() {
      const value = this.ruleForm.unitPrice.trim();
      const reg = /^\d*$/;
      if (!reg.test(value)) {
        this.ruleForm.unitPrice = value.replace(/[^\d.]/g, '');
      }
    },
    handleBlur() {
      const value = this.ruleForm.unitPrice.trim();
      if (/^\d+$/.test(value)) {
        this.ruleForm.unitPrice = value + '.00';
      }
    },
    // 选中人民币就选中国内
    changeOptions(parsms) {
      console.log('tag', parsms)
      if (parsms == 'CNY' || parsms == 1) {
        this.ruleForm.deliveryPlace = 'FArea01'
      } else {
        this.ruleForm.deliveryPlace = 'FArea02'
      }
    },
    handlesupplierChange(v) {
      let sup = this.suppliers.find((x) => x.supplierID == v);
      if (sup) {
        this.ruleForm.supplierName = sup.supplierName;
      } else {
        this.ruleForm.supplierName = undefined;
      }
    },
    handleConfirmQuto() {
      this.btnLoading = true;
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 表示从搜商机过来的
          // console.error(this.ruleForm);
          if (this.isSommer || this.isHome) {
            if (this.ruleForm.currency == "人民币") {
              this.ruleForm.currency = 1
            } else {
              this.ruleForm.currency = 2
            }
            SearchQuote({
              inquiryID: "",
              inquiryItemID: this.qutoData.inquiryItemID || this.qutoData.id,
              unitPrice: this.ruleForm.unitPrice,
              currency: this.ruleForm.currency,
              quantity: this.ruleForm.quantity,
              deliveryDate: this.ruleForm.deliveryDate,
              termDate: this.ruleForm.deliveryDate,
              dateCode: this.ruleForm.dateCode,
              deliveryPlace: this.ruleForm.deliveryPlace,
              supplierID: this.ruleForm.supplierID,
              supplierName: this.ruleForm.supplierName,
              summary: undefined,
            })
              .then((res) => {
                if (res.status == 200) {
                  // this.$msgbox({
                  //   title: "",
                  //   message: "已收到您的申请，请等待采购确认后 进行报价",
                  //   showCancelButton: true,
                  //   confirmButtonText: "确定",
                  //   cancelButtonText: "取消",
                  //   customClass: "noname",
                  //   center: true,
                  //   dangerouslyUseHTMLString: true,
                  // })
                  // .then((action) => { });
                  this.$emit("close");
                  this.$message.success("报价成功");
                  this.btnLoading = false;
                  this.$store.dispatch("sidebars/getInquiryTotal", {
                    userId: this.id
                  });
                }
              })
              .catch(() => {
                this.btnLoading = false;
              });
          } else {
            if (this.ruleForm.currency == "人民币") {
              this.ruleForm.currency = 1
            } else {
              this.ruleForm.currency = 2
            }
            console.log('tag', this.qutoData)
            TaskQuote({
              inquiryID: this.qutoData.inquiryID,
              inquiryItemID: this.qutoData.product_id,
              unitPrice: this.ruleForm.unitPrice, // 报价
              currency: this.ruleForm.currency, // currency
              quantity: this.ruleForm.quantity, // 报价数量
              deliveryDate: this.ruleForm.deliveryDate, // 交货日期
              dateCode: this.ruleForm.dateCode, // 批次
              deliveryPlace: this.ruleForm.deliveryPlace, // 交货地
              supplierID: this.ruleForm.supplierID, // 报价公司
              supplierName: this.ruleForm.supplierName, // 报价公司
              termDate: this.ruleForm.termDate, // 报价有效期
              summary: undefined,
            })
              .then((res) => {
                if (res.status == 200) {
                  this.$emit("close");
                  this.$message.success("报价成功");
                  this.$store.dispatch("sidebars/getInquiryTotal", {
                    userId: this.id
                  });
                }
                this.btnLoading = false;
              })
              .catch(() => {
                this.btnLoading = false;
              });
          }
        } else {
          this.btnLoading = false;
        }
      });
    },
    handleAccept() {
      // unitPrice 报价
      // currency  币种
      // quantity 报价数量
      // deliveryDate 交货日期
      // dateCode 批次
      // deliveryPlace  交货地
      // termDate 报价有效期
      // supplierID 报价公司
      if (this.isAccept) {
        this.$set(this.ruleForm, "unitPrice", (this.qutoData.unitPrice || this.qutoData.adoptPrice) ? (this.qutoData.unitPrice || this.qutoData.adoptPrice).toFixed(2) : 0
        );
        this.$set(this.ruleForm, "currency", (this.qutoData.currency == 1 || this.qutoData.currency == 'CNY') ? "人民币" : "美元");
        this.$set(this.ruleForm, "quantity", this.qutoData.quantity);
        this.$set(this.ruleForm, "deliveryDate", this.qutoData.deliveryDate);
        this.$set(this.ruleForm, "dateCode", this.qutoData.dateCode);
        this.$set(this.ruleForm, "deliveryPlace", this.qutoData.deliveryPlace || this.qutoData.district);
      } else {
        this.$refs["form"].resetFields();
      }
    },
    // 无法报价
    handleNotQuto() {
      this.btnLoading = true;
      this.$confirm("确认取消报价?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.isSommer || this.isHome) {
            if (this.isSommer) {
              this.qutoData.inquiryItemID = this.qutoData.inquiryItemID
            } else if (this.isHome) {
              this.qutoData.inquiryItemID = this.qutoData.id
            }
            UnableQuote({ ids: [this.qutoData.inquiryItemID], reason: "" }).then((res) => {
              if (res.status == 200) {
                this.$emit("close");
                this.$message.success("操作成功");
                this.$store.dispatch("sidebars/getInquiryTotal", {
                  userId: this.id
                });
              }
              this.btnLoading = false;
            });
          } else {
            UnableQuote({ ids: [this.qutoData.inquiryID], reason: "" }).then((res) => {
              if (res.status == 200) {
                this.$emit("close");
                this.$message.success("操作成功");
                this.$store.dispatch("sidebars/getInquiryTotal", {
                  userId: this.id
                });
              }
              this.btnLoading = false;
            });
          }

        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消操作",
          });
          this.btnLoading = false;
        });
    },
  },
  filters: {
    manageTime(v) {
      // console.log('tag', v)
      if (!v || isNaN(v)) {
        return v;
      } else {
        // let days = parseInt(v / (1000 * 60 * 60 * 24))
        // let hour = parseInt(v / 3600);
        // let min = parseInt((v - hour * 60 * 60) / 60);
        // let sec = parseInt((v % 3600) - min * 60);
        // return `${hour < 10 ? "0" + hour : hour}:${min < 10 ? "0" + min : min
        //   }:${sec < 10 ? "0" + sec : sec}`;
        // return `${days}天${hour}时${min}分`
        let days = parseInt(v / (60 * 60 * 24));
        let hour = parseInt((v % 86400) / 3600);
        let min = parseInt((v % 3600) / 60);
        return `${days}天${hour}时${min}分`
      }
    },
  },
  directives: {
    inpNum: {
      inserted: function (el, binding) {
        el.oninput = function (v) {
          setTimeout(() => {
            let value = v.target.value;
            if (binding.modifiers.noquto) {
              value = value.replace(/[^\d]+/g, "");
            } else {
              value = value.replace(/[^\d^\.]+/g, "");
            }
            v.target.value = value;
          });
        };
      },
    },
    // remainedTime: {
    //   inserted: function (el, binding) {
    //     let interval = null;
    //     let html = el.innerHTML;
    //     function timex() {
    //       html = el.innerHTML;
    //       if (!html.includes("已结束")) {
    //         let v =
    //           html.split(":")[0] * 3600 +
    //           html.split(":")[1] * 60 +
    //           html.split(":")[2] * 1;
    //         v = v - 1;
    //         if (v <= 0) {
    //           el.innerHTML = "已结束";
    //           binding.value.quoteRemainMin = 0;
    //           interval || clearInterval(interval);
    //         } else {
    //           binding.value.quoteRemainMin = v;
    //           // let hour = parseInt(v / 3600);
    //           // let min = parseInt((v - hour * 60 * 60) / 60);
    //           // let sec = parseInt((v % 3600) - min * 60);
    //           // el.innerHTML = `${hour < 10 ? "0" + hour : hour}:${min < 10 ? "0" + min : min
    //           //   }:${sec < 10 ? "0" + sec : sec}`;
    //             let days = parseInt(v / (60 * 60 * 24));
    //             let hour = parseInt((v % 86400) / 3600);
    //             let min = parseInt((v % 3600) / 60);
    //             el.innerHTML = `${days}天${hour}时${min}分`
    //         }
    //       }
    //     }
    //     if (!html.includes("已结束")) {
    //       timex();
    //       interval = setInterval(() => {
    //         timex();
    //       }, 1000);
    //       if (interval) {
    //         el.setAttribute("data", interval);
    //       }
    //     }
    //   },
    //   unbind: function (el) {
    //     let data = el.getAttribute("data");
    //     if (data) {
    //       clearInterval(data);
    //     }
    //   },
    // },
  },
};
</script>
<style scoped lang="scss" src="@/assets/styles/public.scss"></style>
<style scoped lang="scss">
::v-deep .el-descriptions__header {
  color: #1A2035;
  font-weight: 500;
  font-size: 12px;
  margin-bottom: 15px;

  // .el-descriptions__title{
  //   color: #1A2035;
  //   font-weight: 500;
  //   font-size: 14px;
  // }
  .el-descriptions__title {
    font-size: 14px;
  }
}

::v-deep .el-descriptions__body {
  // margin: 0 20px;
  border: 1px solid #ccc;
  padding: 12px 20px;
  border-radius: 4px;

  .el-descriptions-item__container {
    justify-content: space-between !important;

    .el-descriptions-item__content {
      margin-right: 40px;
    }
  }

  .el-descriptions-item__label {
    color: #999;
    font-size: 12px;
  }

  .el-descriptions-item__content {
    color: #1A2035;
    font-size: 12px;
    font-weight: 400;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

}

.suptitle {
  color: #1A2035;
  display: block;
  font-weight: 600;
  font-size: 14px;
  padding: 15px 0;
}

.el-form {
  // margin: 0 20px;
  border: 1px solid #ccc;
  padding: 12px 20px;
  border-radius: 4px;

  // ::v-deep .el-input,
  // .el-select {
  //   width: 250px;
  // }
  ::v-deep.el-form-item__label {
    font-size: 12px !important;
    color: #999 !important;
  }

  .el-checkbox {
    width: 110px;
    height: 20px;
    line-height: 20px;
    background: #2348E8;
    border-radius: 2px;
    color: #fff;
    text-align: center;

    ::v-deep.el-checkbox__label {
      font-size: 12px !important;
      color: #fff !important;
    }

    ::v-deep.el-checkbox__input {
      .el-checkbox__inner {
        background: #2348E8;
        border-color: #fff;
      }

      .el-checkbox__inner:hover {
        background: #2348E8 !important;
        border-color: #fff !important;
      }
    }

    ::v-deep.el-checkbox__input.is-checked {
      .el-checkbox__inner {
        background: #2348E8 !important;
        border-color: #fff !important;
      }
    }
  }

  //   .el-checkbox__input.is-checked .el-checkbox__inner {
  //   background-color: #3eaf7c;
  //   border-color: #3eaf7c;
  //   border-radius: 50%;
  // }

  .input {
    margin-left: 24px;
  }

  .el-select--small {
    width: 84%;
  }

  .el-input--small {
    width: 84%;
  }

  .el-input-number--small {
    width: 84%;
  }

  ::v-deep .el-form-item__label-wrap {
    margin-left: 0px !important;
  }

  .isAccept {
    ::v-deep .el-form-item__content {
      margin-left: 0px !important;
    }
  }

  .dateCode {
    ::v-deep .el-form-item__label {
      margin-left: 8px !important;
    }

    .dataCodeinput {
      margin-left: 25px;
    }
  }

  .place {
    margin-left: 13px;
  }

  ::v-deep.el-form-item__error {
    // top: 10px;
    left: 66px !important;
  }

  // .el-form-item {
  //     margin-bottom: 18px;
  // }

  ::v-deep .el-input__inner {
    text-align: left;
    color: #1A2035;
  }
}

.foot {
  // margin: 160px 0 0 0;
  display: flex;
  justify-content: center;
  // padding: 10px 20px;
  position: absolute;
  left: 37%;
  bottom: 1%;
}
</style >
 